import { Card } from 'antd';

import type { FormProps } from 'antd';
import { Button, Form, Input } from 'antd';
import { useMeStore } from '../../../store/me';
import { Navigate } from 'react-router-dom';

type FieldType = {
  username?: string;
  password?: string;
};

const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

export default function UsernamePasswordLoginPage() {
  const meStore = useMeStore()

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    meStore.login({ username: values.username!, password: values.password! })
  };

  if (meStore.status.state == "AUTHED") {
    return <Navigate to="/"/>
  }

  return (
    <div>
      <Card style={{ width: 360 }} className="mx-auto" loading={meStore.status.state == "LOADING"} title="用户名密码登录">
        <Form
          name="username-password-login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          layout="vertical"
          size="large"
        >
          <Form.Item<FieldType> label="用户名" name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
            <Input placeholder="请在此输入用户名" />
          </Form.Item>

          <Form.Item<FieldType> label="密码" name="password" rules={[{ required: true, message: '请输入密码!' }]}>
            <Input.Password placeholder="请在此输入密码" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}
